//
//  WFCUFCircleMsgListVC.m
//  WFChatUIKit
//
//  Created by 陈*敏 on 2/6/2024.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUFCircleMsgListVC.h"
 
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "AFNetworking.h"
#import <WFChatClient/WFCChatClient.h>
#import "SDWebImage/UIImageView+WebCache.h"
#import "WFCUImage.h"
#import "MBProgressHUD.h"
#import "UIView+Toast.h"

@interface WFCUFCircleMsgListVC () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@end

@implementation WFCUFCircleMsgListVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ZmNavigationHeight_N(), self.view.frame.size.width, self.view.frame.size.height -  ZmNavigationHeight_N()) style:UITableViewStylePlain];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }

    self.title = @"消息";
    
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];

    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清空" style:UIBarButtonItemStylePlain  target:self action:@selector(clickClear:)  ];
//
    [self getNoticeList ];

}
 
- (void)getNoticeList{
    
    WEAKSELF_ZM
    
    NSString *savedToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
 
    [manager.requestSerializer setValue:savedToken forHTTPHeaderField:@"authToken"];

//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/userTopic/%@" , userId];
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/noticeList" ];
//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/noticeListCount" ];

    
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            
            NSLog(@" ret---  %@ ", dic );
            NSArray *rows = [dic handleNullObjectForKey:@"data"];
            weakSelf.dataArray = rows.mutableCopy;

        }
        
        [weakSelf.tableView reloadData];

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error) {
             
            NSLog(@" ret---  %@ ", error );

        }

        
    }];
}

- (void)clickClear:(BOOL)tip {
    MBProgressHUD *_hud;
    if (tip == NO) {
         
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"加载中...";
        [hud showAnimated:YES];
        _hud = hud;
    }
    

//    /topic/sendTopic
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
 
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/clearNotice"  ];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:nil
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (tip  == NO) {
                 
                [_hud hideAnimated:YES];

            }
            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );

            if([dic[@"code"] intValue] == 200) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"postNoticeList" object:nil userInfo:@{@"dic":@""}];

                if (tip == NO) {
                     
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    hud.mode = MBProgressHUDModeText;
                    hud.label.text = @"清空成功";
                    //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                    [hud hideAnimated:YES afterDelay:1.f];
                    hud.completionBlock = ^{
                      
                        
                        
                    };

                }
                
 
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (tip  == NO) {
                 
                [_hud hideAnimated:YES];

                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = error.localizedDescription;
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            }
        });
        
    }];
    
}



#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    [cell.contentView removeAllSubviews];
    
    
    NSDictionary *dic = self.dataArray[indexPath.row];
    
    NSDictionary *obj3 = [[dic handleNullObjectForKey:@"topicContent"] jk_JSONStringWithDictionary];

    WEAKSELF_ZM
    UIImageView * portraitView = [[UIImageView alloc] init ];
 
    [portraitView sd_setImageWithURL:[NSURL URLWithString:[[dic handleNullObjectForKey:@"portrait"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"]];
    
    [cell.contentView addSubview:portraitView];
    portraitView.sd_layout.centerYEqualToView(cell.contentView).leftSpaceToView(cell.contentView, 15).widthIs(38).heightIs(38);
    portraitView.sh_chain_extend.roundSize(10).modeFill();

    
    UILabel *titleL = [[UILabel alloc] init ];
    [cell.contentView addSubview:titleL];

    titleL.sd_layout.leftSpaceToView(portraitView, 15).topSpaceToView(cell.contentView, 6).autoHeightRatio(0);
    [titleL setSingleLineAutoResizeWithMaxWidth:200];
    titleL.sh_chain_extend.font_size(16).titleColor([UIColor colorWithHexExtendString:@"#1D1D1D"]).title([dic handleNullObjectForKey:@"nickName"]);

    
    UIImageView * collView = [[UIImageView alloc] init ];
    [cell.contentView addSubview:collView];
    collView.sd_layout.centerYEqualToView(portraitView).leftEqualToView(titleL).widthIs(18).heightIs(18);

    UILabel *timeL = [[UILabel alloc] init ];
    [cell.contentView addSubview:timeL];

    timeL.sd_layout.leftEqualToView(titleL).topSpaceToView(collView, 6).autoHeightRatio(0);
    [timeL setSingleLineAutoResizeWithMaxWidth:200];
    timeL.sh_chain_extend.font_size(12).titleColor([UIColor colorWithHexExtendString:@"#8A8A8A"]).title([dic handleNullObjectForKey:@"replyTime"]);
    
    
    UIImageView * rightView = [[UIImageView alloc] init ];
    [cell.contentView addSubview:rightView];
    rightView.sd_layout.centerYEqualToView(portraitView).rightSpaceToView(cell.contentView, 12).widthIs(60).heightIs(60);
    rightView.sh_chain_extend.roundSize(10).modeFill();
    NSArray *list = [obj3 handleNullObjectForKey:@"imgList"];
    if (list.count) {
         
        [rightView sd_setImageWithURL:[NSURL URLWithString:[[list firstObject] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]  ];

    }
    if ([[dic handleNullObjectForKey:@"noticeType"] intValue] == 1) { ///<.点赞>
        collView.sh_chain_extend.image_loc(@"moment_z1");
    } else {
        collView.sh_chain_extend.image_loc(@"moment_pl");
    }
    
    
    
//
//    
// 
//    UIButton *set = [[UIButton alloc] init];
//    [cell.contentView addSubview:set];
//    cell.userInteractionEnabled = YES;
//    set.sh_chain_extend.image_loc(@"me_edit").addTarget_action(self, @selector(setupName));
//    set.sd_layout.centerYEqualToView(cell.contentView).rightSpaceToView(cell.contentView, 5).widthIs(50).heightIs(24);
//    
//    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}




@end
